Technical Q&A TB60
The Initialize Method of Multi-fragment Contextual Menu Plug-ins


Q: I have (or had, anyway) a working contextual menu plug-in. When I add a second code fragment (in this case, an application) to the file, my menu item gets added to the menu twice. It turns out my plug-in's Initialize, ExamineContext, and PostMenuCleanup methods get called twice! What's up?

A: The Menu Manager's 'cfrg' resource parser is somewhat less than perfect. It's trying to instantiate each plug-in in the file, but instead it instantiates the first one over and over again. This means that if you need to build more than one plug-in, you need to build more than one plug-in file. This shouldn't affect many developers, because it's usually less tedious to build a single fragment which adds mutiple items to the menu than to build a fragment per menu item.

But your case doesn't call for multiple menu items or plug-ins; you just want multiple code fragments. You can work around this problem with code resembling the following:

    static MyPlug *gMyPlugInstance; // for working around Radar 1663652

    OSStatus MyPlug::Initialize (Environment *, FSSpec *)
    {
        if (!gMyPlugInstance)
            gMyPlugInstance = this;

        return noErr;
    }

    OSStatus MyPlug::ExamineContext
        (Environment *, AEDesc *aeContext, SInt32 timeOut,
            AEDescList *commandList, Boolean *needMoreTime)
    {
        OSStatus err = noErr;

        *needMoreTime = false;

        if (gMyPlugInstance == this)
        {
            if (aeContext)
            {
                // examine the context and add menu items as appropriate
            }
        }

        return err;
    }

[Apr 05 1999]


Developer Documentation | Technical Notes | Development Kits | Sample Code